package com.etone.smartAudit.service;

import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.AdminPermission;
import com.etone.smartAudit.mapper.AdminMapper;
import com.etone.smartAudit.mapper.AdminPermissionMapper;
import com.etone.smartAudit.mapper.AdminRoleMapper;
import com.etone.smartAudit.utils.VerifyUtil;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 蒋学伟
 * @date: 2018-10-12 14:54:16
 * @description:
 */
@Service
@AllArgsConstructor
public class AuthService implements UserDetailsService {

    private AdminMapper adminMapper;

    private AdminRoleMapper adminRoleMapper;

    private AdminPermissionMapper adminPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Admin admin = adminMapper.findByAccount(s);
        if (admin == null) {
            return null;
        }
        List<AdminPermission> adminPermissions;
        if (admin.isAdmin()) {
            adminPermissions = adminPermissionMapper.findAll();
        } else {
            adminPermissions = adminPermissionMapper.findByRoleIds(Arrays.asList(admin.getRole().getId()));
        }
        List<SimpleGrantedAuthority> authorities = adminPermissions.stream().filter(adminPermission -> adminPermission != null).map(adminPermission -> new SimpleGrantedAuthority(adminPermission.getName())).collect(Collectors.toList());
        return new User(admin.getAccount(), admin.getPassword(), authorities);
    }

    /**
     * 获取验证码
     *
     * @param width
     * @param complexity
     * @param uuid
     * @param response
     */
    @Cacheable(value = "verifyCode", key = "'verifyCode:' + #uuid")
    public String getVerifyCode(Integer width, Integer complexity, String uuid, HttpServletResponse response) {
        if (response == null) {
            return "";
        }
        String verifyCode = VerifyUtil.createVerify(response, width, complexity);
        return verifyCode;
    }

    /**
     * 删除缓存
     *
     * @param uuid
     */
    @CacheEvict(value = "verifyCode", key = "'verifyCode:' + #uuid")
    public void deleteVerifyCode(String uuid) {
    }
}